package com.police.activity;
/**
 * 
 */
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.*;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.police.R;
import com.police.controller.*;
import com.police.db.DBHelper;
import com.police.db.UserManager;

import java.util.HashMap;
import java.util.Map;
/**
 * android:text="abc-12345678-00003" 
 * android:text="10003" 
 * @author mac
 *
 */
public class LoginActivity extends BaseActivity {
	Controller HTTP = DefaultController.getHttpClient();
	EditText userEditText;
	EditText passwordEditText;
	CheckBox isAdmin;
	TextView forgetPassword;
	TextView login_button;
    private String iMei;
	ProgressDialog dialog;
	private boolean isIMeiOk = false;
	
	OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.input_user:

				break;
			case R.id.input_password:

				break;
			case R.id.forget_pwd:
				forgetPassword();
				break;
			case R.id.login_button:
				requestImeiNum();
//				if (isIMeiOk) {
//					if (isAdmin.isChecked()) {
//						handleLogin();
//					} else {
//						// 查询数据库
//						loginByUnAdmin();
//					}
//				} else {
//					Toast.makeText(LoginActivity.this, "已欠费，不能登录", 5000).show();
//				}
				break;
			default:
				break;
			}
		}

	};

	/**
	 * 非管理员登录
	 */
	private void loginByUnAdmin() {
		DBHelper helper = new DBHelper(LoginActivity.this);
		UserManager userManager = new UserManager(helper);
		boolean isExist = userManager.queryByLogin(userEditText.getText()
				.toString(), passwordEditText.getText().toString());
		if (isExist) {

			/**
			 * 非管理员登陆
			 */
			// SharedPreferences.Editor editor = preferences.edit();
			// editor.putBoolean("isAdmin", false).commit();
			// editor.putString("loginUserName",
			// userEditText.getText().toString());
			// editor.putString("loginPassWord",
			// passwordEditText.getText().toString());
			saveLoginUserInfo(false, userEditText.getText().toString(),
					passwordEditText.getText().toString());

			// 登录成功
			Intent intent = new Intent(LoginActivity.this, MainActivity.class);
			startActivity(intent);
			LoginActivity.this.finish();
		} else {
			Toast.makeText(LoginActivity.this, "该用户不存在", 5000).show();
		}
	}

	private void saveLoginUserInfo(boolean isAdmin, String loginUserName,
			String loginUserPassWord) {
		SharedPreferences.Editor editor = preference.edit();
		editor.putBoolean("isAdmin", isAdmin).commit();
		editor.putString("loginUserName", loginUserName).commit();
		editor.putString("loginPassWord", loginUserPassWord).commit();
	}

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login_layout);
		/**
		 * 建立一个本地文件,用于保存小数据
		 */
		initPages();
	}

	/**
	 * 忘记密码
	 */
	private void forgetPassword() {

		new AlertDialog.Builder(this)
				.setTitle("忘记密码提示")
				.setMessage(
						"系统管理员密码遗失请拨打0371-86182159,24小时专员确认身份后为您重置密码.普通用户密码遗失,请联系您的系统管理员")
				.setPositiveButton("关闭", null).show();

	}

	private void initPages() {
		forgetPassword = (TextView) findViewById(R.id.forget_pwd);
		userEditText = (EditText) findViewById(R.id.input_user);
		passwordEditText = (EditText) findViewById(R.id.input_password);
		isAdmin = (CheckBox) findViewById(R.id.isAdmin);
		login_button = (TextView) findViewById(R.id.login_button);
		userEditText.setOnClickListener(onClickListener);
		passwordEditText.setOnClickListener(onClickListener);
		login_button.setOnClickListener(onClickListener);
		forgetPassword.setOnClickListener(onClickListener);
		dialog = new ProgressDialog(LoginActivity.this);
		dialog.setMessage("正在登录，请稍候...");
		
		
		isAdmin.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {
//					userEditText.setText("abc-12345678-00003");
//					passwordEditText.setText("10003");
					
//					userEditText.setText("abc-12345678-00003");
//					passwordEditText.setText("10003");
					userEditText.setFocusable(false);
					userEditText.setEnabled(false);
//					passwordEditText.setFocusable(false);
//					passwordEditText.setEnabled(false);
					userEditText.setText("系统管理员");
					passwordEditText.setHint("请输入系统管理员密码");
					getImei();
				}
			}
		});
	}

	private void handleLogin() {
		Map<String, String> map = new HashMap<String, String>();
//		map.put("userid", userEditText.getText().toString());
//		map.put("userpwd", passwordEditText.getText().toString());
		
		map.put("userid", iMei);
		map.put("userpwd", passwordEditText.getText().toString());
		
		HTTP.post(new DefaultRequest("login", map), new AsyncHandler() {

			@Override
			public void onStart() {
				// TODO Auto-generated method
				  dialog.show();
				super.onStart();

			}

			@Override
			public void onSuccess(JSONResp response) {
				// {result:'-1',info:'数据库异常'}
				// {result:'-1',info:'用户设备号或密码不存在！'}
				// {result:'-1',info:'设备编号或密码参数必须存在!'}
				// {result:'1',info:'登录成功'}
				try {
					Toast.makeText(LoginActivity.this,
							response.getString("info"), 5000).show();
					int result = response.getInt("result");
					if (IResponse.Success == result) {// 登录成功
						saveLoginUserInfo(true, userEditText.getText()
								.toString(), passwordEditText.getText()
								.toString());
						Intent intent = new Intent(LoginActivity.this,
								MainActivity.class);
						startActivity(intent);
						LoginActivity.this.finish();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				if(dialog!=null){
					dialog.dismiss();
				}
				super.onSuccess(response);
			}

			@Override
			public void onFailure(Throwable e, String response) {
				Toast.makeText(LoginActivity.this, response, 5000).show();
				PublicTool.getIntence(LoginActivity.this).missDialog();
				super.onFailure(e, response);
			}
		});
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (this.getResources().getConfiguration()
				.equals(Configuration.ORIENTATION_LANDSCAPE)) {
			// L
		} else if (this.getResources().getConfiguration()
				.equals(Configuration.ORIENTATION_PORTRAIT)) {
			// P
		}
	}
	
	
	/**
	 * 得到设备的imei号
	 */
	private void getImei() {
		TelephonyManager telephonyManager=(TelephonyManager) LoginActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
		iMei = telephonyManager.getDeviceId();
	}
	
	
	/**
	 * 发送终端的imei号
	 */
	private boolean requestImeiNum() {
		isIMeiOk = false;
		getImei();
		Map<String, String> map = new HashMap<String, String>();
		map.put("userid", iMei);
		HTTP.post(new DefaultRequest("imei", map), new AsyncHandler() {

			@Override
			public void onStart() {
				// TODO Auto-generated method
				dialog.setMessage("正在检测imei号...");
				  dialog.show();
				super.onStart();
			}

			@Override
			public void onSuccess(JSONResp response) {
				try {
					int result = response.getInt("result");
					if (-1 == result) {// 失败
						isIMeiOk = false;
					    Toast.makeText(LoginActivity.this, "已欠费，不能登录", 5000).show();
//						isIMeiOk = true;
//							if (isAdmin.isChecked()) {
//								handleLogin();
//							} else {
//								// 查询数据库
//								loginByUnAdmin();
//						}
					} else {
						isIMeiOk = true;
							if (isAdmin.isChecked()) {
								handleLogin();
							} else {
								// 查询数据库
								loginByUnAdmin();
						} 
						
						
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				if(dialog!=null){
					dialog.dismiss();
				}
				super.onSuccess(response);
			}

			@Override
			public void onFailure(Throwable e, String response) {
				Toast.makeText(LoginActivity.this, response, 5000).show();
				PublicTool.getIntence(LoginActivity.this).missDialog();
				super.onFailure(e, response);
			}
		});
		return false;
	}
	
	

    /** 
     * Method which locks and unlocks editText component 
     * @param value our boolean value which using in or if operator 
     */  
//    private void lockUnlock(boolean value) {  
//        if (value) {  
//        	userEditText.setFilters(new InputFilter[] { new InputFilter() {  
//                @Override  
//                public CharSequence filter(CharSequence source, int start,  
//                        int end, Spanned dest, int dstart, int dend) {  
//                    return source.length() < 1 ? dest.subSequence(dstart, dend)  
//                            : "";  
//                }  
//            } });  
//        } else {  
//        	userEditText.setFilters(new InputFilter[] { new InputFilter() {  
//                @Override  
//                public CharSequence filter(CharSequence source, int start,  
//                        int end, Spanned dest, int dstart, int dend) {  
//                    return null;  
//                }
//
//            } });  
//        }  
//    }  
}
